package com.tek.ding.faceding.network.rx.observable;

import android.content.Context;
import android.util.Log;

import com.tek.ding.faceding.base.BaseView;
import com.tek.ding.faceding.network.exception.ApiException;
import com.tek.ding.faceding.network.exception.BaseException;
import com.tek.ding.faceding.network.rx.ProgressDialogHandle;

import java.util.Objects;

import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.disposables.Disposable;

/**
 * 加载进度圈
 */
public abstract class ProgressDialogObservable<T> extends ErrorHandleObservable<T> implements ProgressDialogHandle.OnProgressDialogListener {


    private BaseView baseView;
    private Disposable disposable;
    private ProgressDialogHandle progressDialogHandle;

    public ProgressDialogObservable(Context context, BaseView baseView) {
        super(context);
        this.baseView = baseView;
        this.progressDialogHandle = new ProgressDialogHandle(context, true, this);
    }

    protected boolean isShowDialog() {
        return true;
    }

    @Override
    public void onCancelProgress() {
        //isDisposed():查询是否解除订阅 true 代表 已经解除订阅
        if (disposable != null && !disposable.isDisposed()) {
            //主动解除订阅
            Log.d("onCancelProgress","取消订阅");
            disposable.dispose();
        }
    }


    @Override
    public void onSubscribe(@NonNull Disposable d) {
        disposable = d;
        if (isShowDialog() && null!=progressDialogHandle) {
            this.progressDialogHandle.showProgressDialog();
        }
    }

    @Override
    public void onError(@NonNull Throwable e) {
//        super.onError(e);
        if (isShowDialog() && null != progressDialogHandle) {
            this.progressDialogHandle.dismissProgressDialog();
        }

        if (e instanceof ApiException) {
            // 服务器返回的错误
            String message = e.getMessage();
            if (null != baseView)
                baseView.showError(message);
        } else {
            // 未知/服务器错误
            if (null != rxErrorHandle) {
                BaseException baseException = rxErrorHandle.handleError(e);
                if (baseException == null) {
                    e.printStackTrace();
                    Log.d("ErrorHandleObservable", Objects.requireNonNull(e.getMessage()));
                } else {
                    //显示信息
                    if (null != baseView)
                        baseView.showError(baseException.getMessage());
                }
            }
        }
    }

    @Override
    public void onComplete() {
        if (isShowDialog() && null != progressDialogHandle) {
            this.progressDialogHandle.dismissProgressDialog();
        }
    }

}
